#!/bin/bash

source Scripts/script_lib.sh || exit 1

printHelp() {
  echo "-u 可以接受3种参数。1.OSS地址 {\"framework\":\"...\",\"cookeddata\":\"...\"}  2.framework的git url 3.MetaWorld的tag"
  echo "-v BUILD_VERSION GPark的目标版本, 例如：1.5.0"
  echo "-d MW包的DSVersion"
  echo "-i CI_PIPELINE_ID"
  echo "-w WEB_HOOK_URI"
  echo "-b MW_BRANCH"
  echo "-e MW_ENV。 online-oversea or pre-oversea"
  echo "-c MW_BUILD_CONFIG。Development or Shipping"
  echo "-r GPark分支"
  echo "-s Pipeline的触发来源"
  echo "-o DSYM的URL"
  exit 10000
}

while getopts 'u:v:d:i:w:b:e:c:r:s:o:' OPT; do
  case $OPT in
    u) URL="$OPTARG";;
    v) BUILD_VERSION="$OPTARG";;
    d) DS_VERSION="$OPTARG";;
    i) PIPELINE_ID="$OPTARG";;
    w) WEB_HOOK_URI="$OPTARG";;
    b) MW_BRANCH="$OPTARG";;
    e) MW_ENV="$OPTARG";;
    c) MW_BUILD_CONFIG="$OPTARG";;
    r) CI_COMMIT_REF_NAME="$OPTARG";;
    s) CI_PIPELINE_SOURCE="$OPTARG";;
    o) ORIGINAL_INFO="$OPTARG";;
    ?) printHelp;;
  esac
done

if [ -z "$URL" ]; then
  echo "URL: $URL is empty"
  printHelp
fi

if [ -z "$BUILD_VERSION" ]; then
  echo "BUILD_VERSION: $BUILD_VERSION is empty"
  printHelp
fi

release_metaworld() {
  # 1.更新MetaWorld
  # 1.1.清空工作区
  rm -rf Scripts/jenkinsscripts

  # 1.2.clone jenkins脚本到工作区中
  git clone git@gitlab.appshahe.com:product/jenkinsscripts.git Scripts/jenkinsscripts -b feature/automation_v2 --single-branch --depth 1  || exit 10001
  pushd Scripts/jenkinsscripts

  rm -rf Scripts/metaworldbuildnumber
  # 2.2.把jenkinsbuildnumber clone到工作区中
  git clone git@gitlab.appshahe.com:ios-automation/modularizationbuildnumber.git Scripts/metaworldbuildnumber -b main || exit 10005
  pushd Scripts/metaworldbuildnumber
  # 2.3.生成一个build number
  MW_VERSION=$(sh generate_metaworld_tag.sh -n -q) || exit 10005
  popd

  # 1.3.复用Jenkins脚本, 更新MetaWorld
  RELEASE_RESULT=`ruby ModularizationRelease/metaworld_pipeline.rb "$URL" "$MW_VERSION" || exit 10002`
  if [[ "RELEASE_RESULT" =~ "Build command failed" ]]; then
    echo "打包MetaWorld失败"
    exit 10002
  fi
  popd

  # 1.4.清除工作区
  rm -rf Scripts/jenkinsscripts

  # 1.5.更新MetaWorld
  pod mod update MetaWorld --version=$MW_VERSION || exit 10004
}

# 从远端下载MW的dSYM文件
download_mw_dsym() {
  echo "URL: $URL"
  MW_DSYM_URL=$(echo "$ORIGINAL_INFO" | grep -o '"dsyms": "[^"]*"' | sed 's/"dsyms": "\(.*\)"/\1/')
  echo "MW_DSYM_URL: $MW_DSYM_URL"
  if [[ -n "$MW_DSYM_URL" ]]; 
  then
    BASE_DIR="Pods/MetaWorld/MetaWorld/Framework"

    echo "Start download MW dsyms"
    if [[ -f "$BASE_DIR/dsyms.zip" ]]; 
    then
      echo "Deleting existing $BASE_DIR/dsyms.zip..."
      rm -rf "$BASE_DIR/dsyms.zip"
    fi
    curl -o "$BASE_DIR/dsyms.zip" $MW_DSYM_URL || exit 10013

    echo "Unzip dsyms.zip"
    if [[ -d "$BASE_DIR/Shipping" ]]; 
    then
      rm -rf "$BASE_DIR/Shipping"
    fi
    if [[ -f "$BASE_DIR/MetaWorldMobile.framework.dSYM" ]]; then
      rm -rf "$BASE_DIR/MetaWorldMobile.framework.dSYM"
    fi
    unzip "$BASE_DIR/dsyms.zip" -d "$BASE_DIR"

    echo "Rename MetaWorldMobile.framework with MetaWorldMobile.framework.dSYM"
    rm -rf "$BASE_DIR/Shipping/MetaWorldMobile.framework.dSYM"
    mv "$BASE_DIR/Shipping/MetaWorldMobile.dSYM" "$BASE_DIR/MetaWorldMobile.framework.dSYM"

    echo "移除临时文件"
    rm -rf "$BASE_DIR/dsyms.zip"
    rm -rf "$BASE_DIR/Shipping"
  fi
}

# 修改pod的copy framework sh, 使其在build时，嵌入dSYM
hook_copy_framework() {
  echo 'install_dsym "${PODS_ROOT}/MetaWorld/MetaWorld/Framework/MetaWorldMobile.framework.dSYM"' >> "./Pods/Target Support Files/Pods-Project-GPark/Pods-Project-GPark-frameworks.sh"
}

TAG_REGEX="[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2}$"
echo "IOS_DOWNLOAD_URL: $URL"
if [[ $URL =~ $TAG_REGEX ]]
then
  echo "Build without release"
  MW_VERSION=$URL
  pod mod update MetaWorld --version=$URL || exit 10004
else
  echo "Build with release"
  release_metaworld
fi

echo $MW_VERSION > .tag.txt

# 2.发布GPark
# 2.1.清空工作区 
rm -rf Scripts/jenkinsbuildnumber
# 2.2.把jenkinsbuildnumber clone到工作区中
git clone git@gitlab.appshahe.com:product/jenkinsbuildnumber.git Scripts/jenkinsbuildnumber -b master || exit 10005
pushd Scripts/jenkinsbuildnumber
# 2.3.生成一个build number
BUILD_NUMBER=$(sh build-number.sh -n -q) || exit 10005
popd
# 2.4.清空工作区
rm -rf Scripts/jenkinsbuildnumber

echo $BUILD_NUMBER > .buildnumber.txt

refresh_pod_and_enable_branch true || exit 10006

echo "Set Build_Number & Build_Version of project plist"
/usr/libexec/PlistBuddy -c "set :CFBundleVersion ${BUILD_NUMBER}" "GPark/Info.plist" \
|| /usr/libexec/PlistBuddy -c "add :CFBundleVersion string ${BUILD_NUMBER}" "GPark/Info.plist" \
|| exit 10007
/usr/libexec/PlistBuddy -c "set :CFBundleShortVersionString ${BUILD_VERSION}" "GPark/Info.plist" \
|| /usr/libexec/PlistBuddy -c "add :CFBundleShortVersionString string ${BUILD_VERSION}" "GPark/Info.plist" \
|| exit 10008

echo "Set Build_Number & Build_Version of project agv"
xcrun agvtool new-marketing-version "${BUILD_VERSION}" || exit 10008
xcrun agvtool new-version -all "${BUILD_NUMBER}" || exit 10007

echo "Match evironment"
# Match出环境信息并且将首字母大写
[[ "$MW_ENV" =~ .*-(online|pre)-.* ]] && RESULT=`echo ${BASH_REMATCH[1]}`
UPPERCHAR="$(echo $RESULT | cut -c1 | tr '[:lower:]' '[:upper:]')"
ENV="${UPPERCHAR}$(echo $RESULT | cut -c2-)"

# 建立Online -> Release的映射
if [[ $ENV = 'Online' ]];
then
  ENV='Release'
fi

echo "Current ENV is $ENV"

# 进入fastlane archive阶段
# Check fastlane version
fastlane --version || exit 10010

if [[ -n "$ENV" ]];
then
  echo "archive_oversea: $ENV"

  download_mw_dsym
  hook_copy_framework

  fastlane archive_and_upload_testflight env:"$ENV" version:"$BUILD_VERSION" number:"$BUILD_NUMBER" || exit 10011

  echo "上传符号表"
  sh upload_dsyms.sh
else
  echo "archive_normal: $ENV"

  download_mw_dsym
  hook_copy_framework

  fastlane archive_normal env:'Test' || exit 10011
  PGYER_APP_ID='1072956f12bbb140a3eb910bba453c59'

  UPLOAD_RESULT=$(sh Scripts/upload_to_pgyer.sh -k "$PGYER_APP_ID" -t 2 -p 869233 "`pwd`/GPark.ipa") || exit 10012
  echo "UPLOAD_RESULT: $UPLOAD_RESULT"

  # 3.构造飞书推送消息

  # 3.1.读取PGYER_VERSION
  [[ "${UPLOAD_RESULT}" =~ \"buildBuildVersion\":\"([0-9]+)\" ]] && PGYER_VERSION=`echo ${BASH_REMATCH[1]}`
  # 3.2.读取QRCode
  [[ "${UPLOAD_RESULT}" =~ \"buildQRCodeURL\":\"([\:\_\.\/\\A-Za-z0-9\-]+)\" ]] && PGYER_QRCODE=`echo ${BASH_REMATCH[1]}`

  echo "$PGYER_VERSION" > .pgyerversion.txt
  echo "$PGYER_QRCODE" > .pgyerqrcode.txt

  echo "上传符号表"
  sh upload_dsyms.sh
fi

